package com.sz.common.base.utils;

import com.sz.common.base.logger.Logger;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Entities;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;

/**
 * Function: TODO: ADD FUNCTION <br>
 * Author: qiankun<br>
 * Date: 2017-07-20 15:08:00
 */
public class FreeMarkerTemplateUtils {
    public static final String UTF_8 = "UTF-8";
    private static Logger logger = Logger.getLogger(FreeMarkerTemplateUtils.class);
    private static Configuration freemarkerCfg = null;

    static {
        freemarkerCfg = new Configuration();
        try {
            Resource resource = new ClassPathResource(File.separator+"templates");
            File file = resource.getFile();
            freemarkerCfg.setDirectoryForTemplateLoading(file);
        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
    }

    public static String freeMarkerRender(Map<String, Object> data, String htmlTmp) {
        Writer out = new StringWriter();
        try {
            Template template = freemarkerCfg.getTemplate(htmlTmp);
            template.setEncoding(UTF_8);
            template.process(data, out);
            out.flush();
            return out.toString();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        } finally {
            try {
                out.close();
            } catch (IOException ex) {
                ex.printStackTrace();
                logger.error(ex.getMessage());
            }
        }
        return null;
    }


    /**
     * 清理HTML内容,转换成标准xhtml
     * @param contentHtml
     * @return
     */
    public static String tidyHtml(String contentHtml ){
        Document doc = Jsoup.parse(contentHtml);
        doc.outputSettings().escapeMode(Entities.EscapeMode.xhtml);
        doc.outputSettings().prettyPrint(true);
        doc.outputSettings().syntax(Document.OutputSettings.Syntax.xml);
        return doc.html();
    }
}
